package webmarket.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import webmarket.common.CommonMethods;
import webmarket.common.DataTablesParamUtility;
import webmarket.common.DatatableResponse;
import webmarket.common.ShopcategoryController;
import webmarket.controller.transferobjects.JQueryDataTableParamModel;
import webmarket.controller.transferobjects.MerchandiseTO;
import webmarket.jpacontrollers.ShopJpaController;
import webmarket.jpacontrollers.UserJpaController;
import webmarket.model.Merchandise;
import webmarket.model.User;

@Controller
@RequestMapping("/profile")
public class ProfileController extends ControllerBase {

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView profile(ModelMap model) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		model.put("currentUser", true);
		// Must be authenticated, else can not reach this URL
		return profile(model, authentication.getName());
	}

	@RequestMapping("/addMoney")
	public String profile_addmoney(ModelMap model) {
		UserJpaController ujc = new UserJpaController();
		ujc.addMoney(ujc.getCurrent().getId(), 10000);
		return "redirect:/profile";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/{username}")
	public ModelAndView profile(ModelMap model, @PathVariable String username) {
		UserJpaController ujc = new UserJpaController();
		User user;
		user = ujc.getByUsername(username);
		if (user == null) {
			// User does not exist
			return new ModelAndView("redirect:/error/" + ErrorController.ErrorTypes.UserNotExists, model);
		}
		model.put("currentUserCity", ujc.getCurrent().getCity());
		model.put("user", user);
		return new ModelAndView("profile", model);
	}

	@RequestMapping(method = RequestMethod.GET, value = "/sales")
	public ModelAndView profile_merch(ModelMap model) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		model.put("currentUser", true);
		// Must be authenticated, else can not reach this URL
		return profile_merch(model, authentication.getName());
	}

	@RequestMapping(method = RequestMethod.GET, value = "/{username}/sales")
	public ModelAndView profile_merch(ModelMap model, @PathVariable String username) {
		UserJpaController ujc = new UserJpaController();
		User user;
		user = ujc.getByUsername(username);
		if (user == null) {
			// User does not exist
			return new ModelAndView("redirect:/error/" + ErrorController.ErrorTypes.UserNotExists, model);
		}
		model.put("username", username);
		model.put("categoryOptions", ShopcategoryController.getForSelect());
		return new ModelAndView("profile_sales", model);
	}

	@RequestMapping(value = "/sales/getSales")
	public @ResponseBody
	DatatableResponse<MerchandiseTO> profile_merch(HttpServletRequest request) {
		JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);
		logger.debug(param.toString());
		DatatableResponse<MerchandiseTO> response = new DatatableResponse<MerchandiseTO>(param);
		String sortCol = param.getSortColumnName();
		String sortDir = param.sSortDirection;
		int limit = param.iDisplayLength;
		int offset = param.iDisplayStart;
		String username = request.getParameter("username");
		String categoryIdString = request.getParameter("categoryId");
		Integer categoryId = null;
		if (!StringUtils.isBlank(categoryIdString) && !categoryIdString.equals("0")) {
			categoryId = Integer.parseInt(categoryIdString);
		}
		ShopJpaController sjc = new ShopJpaController();
		List<Merchandise> merches = sjc.getMerchandises(categoryId, username, null, null, null, sortCol, sortDir, limit, offset);
		response.setData(MerchandiseTO.convert(merches), sjc.getCount(), sjc.getCount(categoryId, username, null, null, null));
		logger.debug(response.toString());
		logger.exit();
		return response;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String editProfile(@RequestParam(value = "edit_userid") int userId,
			@RequestParam(value = "edit_firstname") String firstname,
			@RequestParam(value = "edit_lastname") String lastname,
			@RequestParam(value = "edit_city") String city,
			@RequestParam(value = "edit_address") String address,
			@RequestParam(value = "edit_password", required = false, defaultValue = "") String password) {
		UserJpaController ujc = new UserJpaController();
		User user = ujc.find(userId);
		if (user.getUsername().equals(CommonMethods.getCurrentUserName())) {
			user.setFirstname(firstname);
			user.setLastname(lastname);
			user.setCity(city);
			user.setAddress(address);
			if (!!StringUtils.isBlank(password)) {
				String encodedPassword = DigestUtils.sha1Hex(password);
				user.setPassword(encodedPassword);
			}
			ujc.edit(user);
		} else {
			return "redirect:/error/" + ErrorController.ErrorTypes.UserNotExists;
		}
		return "redirect:/profile";
	}
}
